<template>
    <a-modal
        v-model:visible="showModal"
        :title="title"
        :width="600"
        :destroyOnClose="true"
        :maskClosable="false"
        :confirmLoading="loading"
        @ok="onSubmit"
        @cancel="handleCancle"
    >
        <a-form
            class="user-model"
            layout="horizontal"
            :model="formState"
            :rules="rules"
            ref="formRef"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
        >
            <a-form-item :label="t('yl.userName')" name="username">
                <a-input v-model:value="formState.username" />
            </a-form-item>
            <a-form-item :label="t('yl.passWord')" name="password" v-if="!formState.id">
                <a-input v-model:value="formState.password" />
            </a-form-item>
            <a-form-item :label="t('yl.phone')" name="phone">
                <a-input v-model:value="formState.phone" maxLength="11" />
            </a-form-item>
            <a-form-item :label="t('yl.nickName')" name="nickName">
                <a-input v-model:value="formState.nickName" />
            </a-form-item>
            <a-form-item :label="t('yl.email')" name="email">
                <a-input v-model:value="formState.email" />
            </a-form-item>
            <a-form-item :label="t('yl.dept')">
                <!-- <a-select
                    v-model:value="formState.dept"
                    v-loadmore="loadmore"
                    :allowClear="true"
                    :placeholder="t('yl.pleaseSelectDept')"
                >
                    <a-select-option v-for="item in deptState.list" :key="item.id" :disabled="!item.enabled">
                        {{ item.name }}
                    </a-select-option>
                </a-select> -->
                <yl-treeselect-vue :treeCheckable="false" v-model:value="formState.dept"></yl-treeselect-vue>
            </a-form-item>
            <!-- <a-form-item> </a-form-item> -->
            <a-form-item :label="t('yl.gender')">
                <a-radio-group v-model:value="formState.gender">
                    <a-radio value="男">{{ t('yl.man') }}</a-radio>
                    <a-radio value="女">{{ t('yl.female') }}</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item :label="t('yl.status')" name="enabled">
                <a-radio-group v-model:value="formState.enabled">
                    <a-radio value="1">{{ t('yl.active') }}</a-radio>
                    <a-radio value="0">{{ t('yl.disabled') }}</a-radio>
                </a-radio-group>
            </a-form-item>
            <a-form-item v-if="formState.id"> </a-form-item>
            <a-form-item :label="t('yl.role')" name="roleIds">
                <a-select
                    style="width: 454px"
                    v-model:value="formState.roleIds"
                    mode="multiple"
                    :allowClear="true"
                    :placeholder="t('yl.pleaseSelectRole')"
                >
                    <a-select-option v-for="item in roleState.list" :key="item.id">{{ item.name }}</a-select-option>
                </a-select>
            </a-form-item>
        </a-form>
    </a-modal>
</template>
<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { PaginationQuery } from '@/types/table';
import useRoles from '@/hooks/useRoles';
import useDepts from '@/hooks/useDepts';
import { validators } from '@/utils';
import { UserInfo } from '@/types/user';
import ylTreeselectVue from '@/components/ylTreeselect.vue';
import { delay } from 'lodash';
// 表单校验规则
const initRules = (t: fn) => {
    return {
        username: [{ required: true, message: t('yl.pleaseInputUsername'), trigger: 'blur' }],
        password: [{ required: true, message: t('yl.passWord'), trigger: 'blur' }],
        phone: [{ required: true, message: t('yl.custMoblieValidator'), trigger: 'blur', validator: validators.phone }],
        nickName: [{ required: true, message: t('yl.pleaseEntryNickname'), trigger: 'blur' }],
        email: [{ required: true, message: t('yl.pleaseEntryEmail'), trigger: 'blur', validator: validators.email }],
        dept: [{ required: true, type: 'number', message: t('yl.pleaseSelectDept'), trigger: 'blur' }],
        jobs: [{ required: true, type: 'array', message: t('yl.pleaseSelectPost'), trigger: 'blur' }],
        roleIds: [{ required: true, type: 'array', message: t('yl.pleaseSelectRole'), trigger: 'blur' }],
        enabled: [{ required: true, message: t('yl.status'), trigger: 'blur' }],
    };
};

export default defineComponent({
    name: 'userModel',
    components: {
        ylTreeselectVue,
    },
    props: {
        visible: {
            type: Boolean,
            default: () => false,
        },
        title: {
            type: String,
        },
        loading: {
            type: Boolean,
            default: () => false,
        },
        user: {
            type: Object,
        },
    },
    emits: ['submit', 'cancle'],
    setup(props, { emit }) {
        const { t } = useI18n();
        const showModal = computed(() => props.visible);
        const formState: UserInfo = reactive({
            username: '', // 用户名
            password: '', //密码
            nickName: '', // 昵称
            gender: '男', // 性别
            email: '', // 邮箱
            enabled: '1', // 是否禁用 true
            // roles: [], // 角色
            roleIds: [], //角色ID
            // jobs: [], // 岗位
            dept: '', // 部门
            phone: '', // 手机号
            id: null,
        });

        watch(
            () => props.user,
            (user) => {
                console.log(user);
                const { username, nickName, gender, email, enabled, roles, phone, id, password, dept } = user as NormalObj;
                formState.username = JSON.stringify(user) == '{}' ? '' : username;
                formState.password = JSON.stringify(user) == '{}' ? '' : password;
                formState.nickName = JSON.stringify(user) == '{}' ? '' : nickName;
                formState.gender = JSON.stringify(user) == '{}' ? '' : gender;
                formState.email = JSON.stringify(user) == '{}' ? '' : email;
                formState.enabled = JSON.stringify(user) == '{}' ? '1' : enabled ? '1' : '0';
                formState.phone = phone;
                formState.dept = dept ? dept.id * 1 : '';
                formState.roleIds = roles && roles.length ? roles.map((item: NormalObj) => item.id * 1) : [];
                // formState.jobs = jobs.length ? roles.map((item: NormalObj) => item.id * 1) : [];
                formState.id = id;
                console.log(formState);
            }
        );

        // 分页查询 角色/部门/岗位
        const params: PaginationQuery = {
            page: 0,
            size: 10,
        };
        // 角色集合
        const roleState: NormalizeTableData & PaginationQuery = reactive({
            list: [],
            total: 0,
            ...params,
        });
        // 部门集合
        const deptState: NormalizeTableData & PaginationQuery = reactive({
            list: [],
            total: 0,
            ...params,
        });

        const queryRoles = async (params: PaginationQuery) => {
            const { list, total } = await useRoles(params);
            roleState.list = [...roleState.list, ...list];
            roleState.total = total;
        };
        const queryDepts = async () => {
            const { list, total } = await useDepts();
            deptState.list = [...deptState.list, ...list];
            deptState.total = total;
        };

        onMounted(async () => {
            const timer = window.setTimeout(() => {
                Promise.all([queryRoles(params), queryDepts()]).then(() => {
                    clearTimeout(timer);
                }); // 预留
            }, 1000);
        });

        // 表单校验
        const rules = initRules(t);
        const formRef = ref();
        // 提交
        const onSubmit = () => {
            console.log(formState);
            formRef.value.validate().then(() => {
                let { dept, roleIds } = formState;

                // 多余的操作 接口数据类型问题
                const result = {
                    ...formState,
                    dept: {
                        id: dept,
                    },
                    roleIds: roleIds.map((item) => {
                        // return {
                        //     id: item,
                        // };
                        return item;
                    }),
                };
                result.enabled == '1' ? (result.enabled = true) : (result.enabled = false);
                emit('submit', result);
            });
        };

        // 取消
        const handleCancle = () => {
            return emit('cancle');
        };

        // 滚顶加载
        const loadmore = () => {
            console.log('下计');
        };

        return {
            formRef,
            labelCol: { span: 8 },
            wrapperCol: { span: 16 },
            showModal,
            formState,
            t,
            roleState,
            deptState,
            rules,
            onSubmit,
            handleCancle,
            loadmore,
        };
    },
});
</script>
<style lang="scss" scoped>
.user-model {
    @include flexWrap;
    width: 100%;
    .ant-form-item {
        width: 50%;
        margin-right: 0;
        padding-right: $width10;
        margin-bottom: $width8;
    }
}
</style>
